import mongoose from 'mongoose';
import { config } from './index';

/**
 * 数据库连接配置
 */
class DatabaseConnection {
  private static instance: DatabaseConnection;
  private isConnected: boolean = false;

  private constructor() {}

  /**
   * 获取数据库连接实例（单例模式）
   */
  public static getInstance(): DatabaseConnection {
    if (!DatabaseConnection.instance) {
      DatabaseConnection.instance = new DatabaseConnection();
    }
    return DatabaseConnection.instance;
  }
  
  /**
   * 连接到MongoDB数据库
   */
  public async connect(): Promise<void> {
    // 检查是否已经有活跃的连接（包括测试环境）
    if (this.isConnected || mongoose.connection.readyState === 1) {
      console.log('Database already connected');
      this.isConnected = true;
      return;
    }

    try {
      // 设置Mongoose连接选项
      const options = {
        maxPoolSize: 10, // 连接池最大连接数
        serverSelectionTimeoutMS: 5000, // 服务器选择超时时间
        socketTimeoutMS: 45000 // Socket超时时间
      };

      await mongoose.connect(config.database.url, options);

      this.isConnected = true;
      console.log(`✅ Connected to MongoDB: ${config.database.name}`);

      // 监听连接事件
      this.setupEventListeners();

    } catch (error) {
      console.error('❌ MongoDB connection error:', error);
      throw error;
    }
  }

  /**
   * 断开数据库连接
   */
  public async disconnect(): Promise<void> {
    if (!this.isConnected) {
      return;
    }

    try {
      await mongoose.disconnect();
      this.isConnected = false;
      console.log('✅ Disconnected from MongoDB');
    } catch (error) {
      console.error('❌ MongoDB disconnection error:', error);
      throw error;
    }
  }

  /**
   * 获取连接状态
   */
  public getConnectionStatus(): boolean {
    return this.isConnected && mongoose.connection.readyState === 1;
  }

  /**
   * 设置事件监听器
   */
  private setupEventListeners(): void {
    // 连接成功
    mongoose.connection.on('connected', () => {
      console.log('📡 Mongoose connected to MongoDB');
    });

    // 连接错误
    mongoose.connection.on('error', (error) => {
      console.error('❌ Mongoose connection error:', error);
      this.isConnected = false;
    });

    // 连接断开
    mongoose.connection.on('disconnected', () => {
      console.log('📡 Mongoose disconnected from MongoDB');
      this.isConnected = false;
    });

    // 应用终止时关闭数据库连接
    process.on('SIGINT', async () => {
      await this.disconnect();
      process.exit(0);
    });

    process.on('SIGTERM', async () => {
      await this.disconnect();
      process.exit(0);
    });
  }
}

// 导出数据库连接实例
export const database = DatabaseConnection.getInstance();
export default database;
